package com.asia.algorithmcode.binaryTree;

/**
 * @DESCRIPTION: 108、将有序数组转换成二叉搜索树
 * @USER: wanfu
 * @DATE: 2025/5/12 星期一 11:47
 */
public class SortedArrayToBST {


    public static void main(String[] args) {

        int[] arr = {-10, -3, 0, 5, 9};
        TreeNode treeNode = new SortedArrayToBST().sortedArrayToBST(arr);

        System.out.println();
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        int n = nums.length;
        if (n == 1) {
            return new TreeNode(nums[0]);
        }
        int midIndex = n / 2;
        TreeNode treeNode = new TreeNode(nums[midIndex]);
        treeNode.left = gen(0, midIndex - 1, nums);
        treeNode.right = gen(midIndex + 1, n - 1, nums);
        return treeNode;
    }

    private TreeNode gen(int l, int r, int[] nums) {
        if (l > r) {
            return null;
        }
        int midIndex = l + (r - l) / 2;
        TreeNode tempNode = new TreeNode(nums[midIndex]);
        tempNode.left = gen( l, midIndex - 1, nums);
        tempNode.right = gen(midIndex + 1, r, nums);
        return tempNode;
    }


}
